<template>
  <div class="product-detail">
    <v-title :title="detail.title" :is-center="false" />
    <loading :show="loading" :timeout="loadingTimeout" />
    <arrow :show-top="true" v-if="!showPop" />
    <swiper :swiper="detail.image" />
    <v-desc :detail="detail" @qrcodeShare="qrcodeShare" @changeQuantity="changeQuantity" />
    <f :detail="detail" />
    <freight-city :detail="detail" v-if="true" />
    <v-area :area="detail.area" />
    <group
      v-if="detail.isGroup"
      :group-list="groupList"
      :fans-list="fansList"
      @go="groupGo"
    />
    <sku :detail="detail" />
    <brand :brand="detail.brand" />
    <property :list="detail.properties" v-if="false" />
    <comment :detail="detail" />
    <detail :detail="detail" />
    <v-footer
      :detail="detail"
      @openPop="openPop"
      @addCart="addCart"
      @buy="buy"
      @createGroup="createGroup"
      @joinGroup="joinGroup"
      @randomGroup="randomGroup"
    />
    <pop
      v-if="showPop"
      :type="popType"
      :detail="detail"
      @openPop="openPop"
      @addCart="addCart"
      @buy="buy"
      @createGroup="createGroup"
      @joinGroup="joinGroup"
      @randomGroup="randomGroup"
      @closePop="closePop" />
  </div>
</template>

<script>
import api from '@/api'
import base64 from '@/util/base64'
import Loading from '@/components/Loading'
import Title from '@/components/Title'
import Arrow from '@/components/Arrow'
import Swiper from './components/Swiper'
import Desc from './components/Desc'
import FreightCity from './components/FreightCity'
import F from './components/F'
import Comment from './components/Comment'
import Detail from './components/Detail'
import Brand from './components/Brand'
import Property from './components/Property'
import Sku from './components/Sku'
import Area from './components/Area'
import Footer from './components/Footer'
import Pop from './components/Pop'
import Group from './components/Group'
import scroll from '@/util/scroll'
export default {
  name: 'ProductDetail',
  components: {
    Loading,
    'v-title': Title,
    F,
    Arrow,
    Swiper,
    'v-desc': Desc,
    FreightCity,
    Comment,
    Detail,
    'v-footer': Footer,
    Brand,
    'v-area': Area,
    Property,
    Sku,
    Pop,
    Group
  },
  data() {
    return {
      loading: false,
      detail: {},
      showPop: false,
      popType: 0,
      loadingTimeout: 200,
      groupList: [],
      fansList: [],
      groupQuantity: 10,
      quantity: 1
    }
  },
  watch: {
    // disable scroll
    showPop(v) {
      if (v) {
        document.body.style.overflow = 'hidden'
      } else {
        document.body.style.overflow = 'auto'
      }
    },
    // 'detail.isGroup': {
    //   handler(v) {
    //     if (v) {
    //       this.getGroupList(this.detail.id)
    //     }
    //   }
    // },
    // clear cache
    $route: {
      handler(v) {
        this.refreshGroup()
        this.refreshFans()
      }
    }
  },
  methods: {
    // 数量
    changeQuantity(n) {
      this.quantity = n
    },
    groupGo(group_id) {
      this.$router.push(`/product/detail/${this.detail.id}/${group_id}`)
    },
    getGroupList(product_id) {
      this.loading = true
      api.Group.groupByProduct({ product_id }).then(response => {
        let { data } = response
        data = base64.parse(data)
        this.groupList = data.list
        this.groupQuantity = data.quantity
      }).finally(() => {
        this.loading = false
      })
    },
    getFansList(group_id) {
      this.loading = true
      api.Group.fansByGroup({ group_id }).then(response => {
        let { data } = response
        data = base64.parse(data)
        this.fansList = data.list
        this.groupQuantity = data.quantity
      }).finally(() => {
        this.loading = false
      })
    },
    fetchData() {
      this.loading = true
      api.Product.detail({ id: this.$route.params.id }).then(response => {
        let { data } = response
        data = base64.parse(data)
        this.detail = data
        // console.log(data)
        // wx share
        this.share(data)
      }).finally(() => {
        this.loading = false
      })
    },
    openPop(v) {
      this.showPop = true
      scroll.toTop()
      this.popType = v
    },
    closePop() {
      this.showPop = false
    },
    getOptions(option = {}) {
      const isEmpty = Object.keys(option).length === 0
      if (isEmpty) {
        // no sku
        return {
          price: this.detail.price,
          product_id: this.$route.params.id,
          quantity: this.quantity
        }
      }
      // selected sku
      return {
        ...option,
        product_id: this.$route.params.id
      }
    },
    addCart(options = {}) {
      // 检测添加购物车
      api.Cart.checkRepeat({ id: this.$route.params.id }).then(() => {
        this.loading = true
        this.loadingTimeout = 1
        api.Cart.addCart({
          // product_id: this.$route.params.id
          ...this.getOptions(options)
        }).then(() => {
          this.$createToast({
            type: 'correct',
            txt: '添加成功',
            time: 500,
            onTimeout: () => {
              this.$router.push('/cart')
            }
          }).show()
        }).finally(() => {
          this.loading = false
          this.loadingTimeout = 200
        })
      })
    },
    buy(options = {}) {
      // this.$router.push({
      //   name: 'order',
      //   params: {
      //     ...this.getOptions(options)
      //   }
      // })
      const next = () => {
        // 没报单, 不能复购
        api.Cart.checkRepeat({ id: this.$route.params.id, no_add: true }).then(() => {
          this.$router.replace({
            name: 'order',
            params: {
              ...this.getOptions(options)
            }
          })
        })
      }
      // 是否重复购买报单区
      api.Cart.checkBuy({ id: this.$route.params.id }).then(response => {
        let { data } = response
        data = base64.parse(data)
        const { result } = data
        if (!result) {
          next()
        } else {
          this.$createDialog({
            type: 'confirm',
            // icon: 'cubeic-alert',
            title: '您已经购买过相同商品',
            // content: '确定继续购买?',
            content: '只能买1次!',
            confirmBtn: {
              text: '确定',
              active: true,
              disabled: false,
              href: 'javascript:;'
            },
            cancelBtn: {
              text: '取消',
              active: false,
              disabled: false,
              href: 'javascript:;'
            },
            onConfirm: () => {
              // this.$createToast({
              //   type: 'warn',
              //   time: 1000,
              //   txt: '点击确认按钮'
              // }).show()
              // next()
            },
            // onCancel: () => {
            //   this.$createToast({
            //     type: 'warn',
            //     time: 1000,
            //     txt: '点击取消按钮'
            //   }).show()
            // }
          }).show()
        }
      })
    },
    createGroup(options = {}) {
      this.$router.push({
        name: 'order',
        params: {
          ...this.getOptions(options),
          create_group: true
        }
      })
    },
    joinGroup(options = {}) {
      this.$router.push({
        name: 'order',
        params: {
          ...this.getOptions(options),
          group_id: this.$route.params.group
        }
      })
    },
    randomGroup(options = {}) {
      this.$router.push({
        name: 'order',
        params: {
          ...this.getOptions(options),
          random_group: true
        }
      })
    },
    refreshFans() {
      const group_id = Number.parseInt(this.$route.params.group || 0)
      if (group_id > 0) {
        this.getFansList(group_id)
      }
    },
    refreshGroup() {
      const id = Number.parseInt(this.$route.params.id || 0)
      if (id > 0) {
        this.getGroupList(id)
      }
    },
    // wx share
    share(detail = false) {
      if (!detail) {
        detail = this.detail
      }
      api.WxShare.share({
        title: detail.title,
        desc: detail.title_sub,
        image: `${window.location.origin}/${detail.mainImage.thumbnail_path}`,
        link: window.location.href
      }).then(() => {
        // 分享成功
      }).catch(() => {
        // 分享失败
      })
    },
    // qrcode share
    qrcodeShare() {
      api.Product.qrcodeShare({
        id: this.$route.params.id,
        url: window.location.href,
        color: {
          background: [255, 255, 255],
          foreground: [106, 86, 235]
        }
      }).then(response => {
        let { data } = response
        data = base64.parse(data)
        this.$createDialog({
          type: 'alert',
          title: '商品二维码',
          content: `<img src="${data.image}" />`
        }).show()
      })
    }
  },
  created () {
    // 产品推荐码
    const id = this.$route.params.group
    if (id) {
      console.log(id)
      // 保存推荐人
      this.$store.dispatch('ExecUser/set_referrer', id).then(() => {
        this.$router.push('/user/register')
      })
    }
    this.refreshGroup()
    this.refreshFans()
  },
  activated () {
    this.fetchData()
    scroll.toTop()
  },
  deactivated () {
  }
}
</script>

<style scoped lang="stylus">
.product-detail
  padding-top 45px
  padding-bottom 55px
</style>
